package com.example.im.ui.fragment

import android.content.Intent
import android.view.View
import androidx.appcompat.app.AlertDialog
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.im.common.Enumerate
import com.example.im.R
import com.example.im.bean.UserRoom
import com.example.im.bean.EventBusData
import com.example.im.ui.activity.RoomActivity
import com.example.im.common.Constants
import com.example.im.mvp.base.BasePresenter
import com.example.im.ui.abstracts.AbstractBaseFragment
import com.example.im.db.DatabaseStorage
import com.example.im.manager.ActivityCollector
import com.example.im.ui.activity.UserActivity
import com.example.im.ui.adapter.FriendRequestAdapter
import com.example.im.ui.adapter.UserRoomAdapter
import com.example.im.utils.JsonUtils
import com.example.im.utils.LogUtils
import com.example.im.xmpp.IMConnection
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.fragment_friend_view_page.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class FriendRequestFragment : AbstractBaseFragment<BasePresenter<*>>(),
    FriendRequestAdapter.OnClickItemListener {

    var userRooms = mutableListOf<UserRoom>()
    var adapter: FriendRequestAdapter? = null

    override val layoutId: Int
        get() = R.layout.fragment_friend_view_page

    override fun initView() {

        EventBus.getDefault().register(this)

        adapter = FriendRequestAdapter(activity!!, userRooms)
        adapter!!.setOnItemClickListener(this)
        recycler_view.layoutManager = LinearLayoutManager(activity)
        recycler_view.adapter = adapter

        Observable.just("")
            .subscribeOn(Schedulers.io())
            .map {
                val userRooms = DatabaseStorage.getUserRoomToRequest()
                if (userRooms == null) {
                    mutableListOf<UserRoom>()
                } else {
                    val users = mutableListOf<UserRoom>()
                    userRooms.forEach { userRoom ->
                        val rows = IMConnection.instance?.getRosterSearch(userRoom.account)
                        if (rows != null) {
                            userRoom.nickname = rows[0].getValues("Name")[0].toString()
                            users.add(userRoom)
                        }
                    }
                    users
                }
            }
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(
                {
                    adapter!!.addDataAll(it)
                },
                {

                }
            )
    }

    override fun initPresenter() {

    }

    override fun initLazyLoad() {

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEventMainThread(eventBus: EventBusData<UserRoom>) {
        if (eventBus.type ?: return != Enumerate.Handle.list_subscribe) {
            return
        }
        when (eventBus.action ?: return) {
            Enumerate.Action.list_add ->
                adapter!!.addDataItem(eventBus.data ?: return)
            Enumerate.Action.list_delete -> {
                adapter!!.removeDataItem(eventBus.data ?: return)
            }
            else -> return
        }
    }


    override fun onDestroyView() {
        super.onDestroyView()
        EventBus.getDefault().unregister(this)
    }

    override fun onClickItem(view: View, position: Int) {

        when (view.id) {
            R.id.tv_new_agree -> {
                val dialog = AlertDialog.Builder(activity!!)
                dialog.setTitle(userRooms[position].nickname)
                dialog.setMessage("是否同意添加对方为好友")
                dialog.setPositiveButton("确定") { d, _ ->
                    val bool = IMConnection.instance!!.setRosterCreate(
                        userRooms[position].jid,
                        userRooms[position].nickname
                    )
                    if (bool) {
                        val user =
                            DatabaseStorage.getUserRoomStorageByAccount(userRooms[position].account!!)
                                ?: return@setPositiveButton
                        val intent = Intent(activity, UserActivity::class.java)
                        intent.putExtra(
                            Constants.BUNDLE_T0_USER_ROOM_POINT,
                            Constants.BUNDLE_T0_USER_POINT_1
                        )
                        intent.putExtra(Constants.BUNDLE_T0_USER_ROOM_DATA, user)
                        activity!!.startActivity(intent)
                    }
                }
                dialog.setNegativeButton("取消", null)
                dialog.show()
            }
            R.id.tv_new_refuse -> {
                val dialog = AlertDialog.Builder(activity!!)
                dialog.setTitle(userRooms[position].nickname)
                dialog.setMessage("是否拒绝添加对方为好友")
                dialog.setPositiveButton("确定") { d, _ ->
                    IMConnection.instance!!.removeRosterEntries(
                        userRooms[position].jid
                    )
                    val eventBus = EventBusData(
                        Enumerate.Handle.list_subscribe,
                        Enumerate.Action.list_delete,
                        userRooms[position]
                    )
                    EventBus.getDefault().post(eventBus)
                }
                dialog.setNegativeButton("取消", null)
                dialog.show()
            }
        }
    }

}